package com.itboye.sunsun.adapter;

import java.util.Iterator;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.sunsunhome.R;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.beans.LunTanCommontBean;
import com.itboye.sunsun.beans.LunTanCommontBean.CommontBean;
import com.itboye.sunsun.beans.LunTanCommontBean.GenTieItemBean;
import com.itboye.sunsun.beans.TieZiQuanXianBean.Group;
import com.itboye.sunsun.constants.NetPublicConstant;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.luntan.ChaKanGengDuoPingKuanActivity;
import com.itboye.sunsun.luntan.TieZiDetailActivity;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.utils.DensityUtil;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.utils.XImageLoader;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.pobing.uilibs.extend.component.dialog.ImageViewerDialog;

public class TieZiCommentAdapter extends BaseExpandableListAdapter {

	LunTanCommontBean commontList;
	TieZiDetailActivity act;
	String myId;
	private CommontBean commontBean;

	public TieZiCommentAdapter(LunTanCommontBean commontList,
			TieZiDetailActivity act) {
		// TODO Auto-generated constructor stub
		this.commontList = commontList;
		this.act = act;

		myId = (String) SPUtils.get(act, null, SPContants.USER_ID, "");
	}

	@Override
	public int getGroupCount() {
		List<GenTieItemBean> beans = commontList.getList();
		return beans == null ? 0 : beans.size();
	}

	@Override
	public int getChildrenCount(int groupPosition) {
		GenTieItemBean gebtiebean = commontList.getList().get(groupPosition);
		List<CommontBean> list = gebtiebean.getComments();

		int c = list == null ? 0 : list.size();
		if (gebtiebean.getViewMore() == 1) {
			c++;
		}

		return c;
	}

	@Override
	public Object getGroup(int groupPosition) {

		return commontList.getList().get(groupPosition);
	}

	@Override
	public Object getChild(int groupPosition, int childPosition) {

		return commontList.getList().get(groupPosition).getComments().get(childPosition);
	}

	@Override
	public long getGroupId(int groupPosition) {

		return groupPosition;
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {

		return childPosition;
	}

	@Override
	public boolean hasStableIds() {

		return false;
	}

	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {
		GroupViewHolder holder;
		if (convertView == null) {
			holder = new GroupViewHolder();
			convertView = LayoutInflater.from(App.ctx).inflate(
					R.layout.item_luntan_gentie, null);

			holder.name = (TextView) convertView.findViewById(R.id.name);
			holder.time = (TextView) convertView.findViewById(R.id.time);
			holder.delete = convertView.findViewById(R.id.delete);
			holder.content = (TextView) convertView.findViewById(R.id.content);
			holder.head = (ImageView) convertView.findViewById(R.id.head);
			holder.pinglun = (ImageView) convertView.findViewById(R.id.pinglun);
			holder.imgsContainer = (ViewGroup) convertView
					.findViewById(R.id.imgsContainer);
			convertView.setTag(holder);

			holder.pinglun.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					final int groupposi = (int) v.getTag();
					//
					View view = LayoutInflater.from(act).inflate(
							R.layout.popupwindow_pinglun_huifu, null);
					final PopupWindow popupWindow = new PopupWindow(view,
							LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT);
					popupWindow.setFocusable(true);
					popupWindow.setOutsideTouchable(true);
					popupWindow.setBackgroundDrawable(new BitmapDrawable());
					popupWindow.showAsDropDown(v);

					view.findViewById(R.id.dianping).setOnClickListener(
							new OnClickListener() {

								@Override
								public void onClick(View v) {
									act.onComment(groupposi);
									popupWindow.dismiss();
								}
							});
					view.findViewById(R.id.huifu).setOnClickListener(
							new OnClickListener() {

								@Override
								public void onClick(View v) {
									act.huifu();
									popupWindow.dismiss();
								}
							});
				}
			});

			holder.delete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					final int groupposi = (int) v.getTag();
					GenTieItemBean genTieItemBean = commontList.getList().get(
							groupposi);
					final String tid = genTieItemBean.getTid();
					final String pid = genTieItemBean.getPid();
					final String fid = genTieItemBean.getFid();
					MyJsonRequest.Builder<String> builder = new MyJsonRequest.Builder<String>()
							.apiVer("100")
							.typeKey("BY_ForumPost_Delete")
							.param("tid", tid)
							.param("fid", fid)
							.param("pid", pid)
							.param("uid",
									(String) SPUtils.get(act, null,
											SPContants.USER_ID, ""))
							.requestListener(new XRequestListener<String>() {

								@Override
								public void onResponse(String orderBean) {

									Toast.makeText(act, "删除成功", 1).show();
									Iterator<GenTieItemBean> itr = commontList
											.getList().iterator();
									while (itr.hasNext()) {
										GenTieItemBean genTieItemBean = itr
												.next();
										if (genTieItemBean.getTid().equals(tid)
												&& genTieItemBean.getPid()
														.equals(pid)
												&& genTieItemBean.getFid()
														.equals(fid)) {
											itr.remove();
										}

									}
									Intent intentS = new Intent("changegroup");
									intentS.putExtra("size", commontList.getList().size());
									act.sendBroadcast(intentS);
									notifyDataSetChanged();

								}
							}).errorListener(new XErrorListener() {

								@Override
								public void onErrorResponse(
										Exception exception, int code,
										String msg) {

								}
							});

					MyJsonRequest<String> request = builder.build();
					HttpRequest.getDefaultRequestQueue().add(request);
				}
			});

		} else {
			holder = (GroupViewHolder) convertView.getTag();
		}

		// if (groupPosition==0) {
		// holder.pinglun.setVisibility(View.INVISIBLE);
		// }else{
		// holder.pinglun.setVisibility(View.VISIBLE);
		//
		// }
		GenTieItemBean genTieItemBean = commontList.getList()
				.get(groupPosition);
		holder.content.setText(genTieItemBean.getMessage());

		if (genTieItemBean.getUserInfo() != null) {
			holder.name.setText(genTieItemBean.getUserInfo().getNickname());
		} else {
			holder.name.setText(genTieItemBean.getAuthor());
		}

		holder.time.setText(genTieItemBean.getDatelineShow());

		try {
			if (genTieItemBean.getUserInfo().getHead() == ""
					|| genTieItemBean.getUserInfo().getHead() == null) {
				Bitmap bitmap = BitmapFactory.decodeResource(
						act.getResources(), R.drawable.defaultimage);
				holder.head.setImageBitmap(bitmap);
			} else {
				holder.head.setImageBitmap(null);
				if (!genTieItemBean.getUserInfo().getHead().startsWith("http")) {
					XImageLoader.load(NetPublicConstant.IMAGE_URL
							+ genTieItemBean.getUserInfo().getHead(),
							holder.head);
				} else {
					XImageLoader.load(genTieItemBean.getUserInfo().getHead(),
							holder.head);
				}
				// XImageLoader.load(NetPublicConstant.IMAGE_URL
				// + genTieItemBean.getUserInfo().getHead(), holder.head);
			}
		} catch (Exception e) {
		}

		holder.pinglun.setTag(groupPosition);
		holder.delete.setTag(groupPosition);
		if (genTieItemBean.getUserInfo() != null) {
			if (myId.equals(genTieItemBean.getUserInfo().getId())) {
				holder.delete.setVisibility(View.VISIBLE);
			} else {
				holder.delete.setVisibility(View.GONE);
			}
		} else if (myId.equals(genTieItemBean.getAuthorId())) {
			holder.delete.setVisibility(View.VISIBLE);
		} else {
			holder.delete.setVisibility(View.GONE);
		}

		final List<String> imgs = genTieItemBean.getImg();
		if (imgs != null && imgs.size() > 0) {
			holder.imgsContainer.setVisibility(View.VISIBLE);
			int width = DensityUtil.dip2px(80);
			int height = DensityUtil.dip2px(100);
			int padd = DensityUtil.dip2px(25);
			int i;
			for (i = 0; i < imgs.size(); i++) {
				String path = imgs.get(i);
				ImageView imageView;
				if (i < holder.imgsContainer.getChildCount()) {
					imageView = (ImageView) holder.imgsContainer.getChildAt(i);
					imageView.setVisibility(View.VISIBLE);
				} else {
					imageView = new ImageView(act);
					imageView.setScaleType(ScaleType.FIT_XY);
					ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(
							width, height);
					android.widget.LinearLayout.LayoutParams layoutParams2 = new android.widget.LinearLayout.LayoutParams(
							width, height);
					// layoutParams2.set
					layoutParams2.setMargins(5, 5, 5, 5);
					holder.imgsContainer.addView(imageView, layoutParams2);
				}
				XImageLoader
						.load(NetPublicConstant.IMAGE_URL + path, imageView);
				final int ii = i;
				imageView.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						ImageViewerDialog dialog = new ImageViewerDialog(act);
						String urls[] = new String[imgs.size()];
						for (int j = 0; j < urls.length; j++) {
							urls[j] = NetPublicConstant.IMAGE_URL + imgs.get(j);
						}
						dialog.setImageUrls(urls);
						dialog.show(ii);
					}
				});
			}
			for (; i < holder.imgsContainer.getChildCount(); i++) {
				holder.imgsContainer.getChildAt(i).setVisibility(View.GONE);
			}

			// for (String string : imgs) {
			// ImageView imageView=new ImageView(act);
			// imageView.setScaleType(ScaleType.CENTER_CROP);
			// ViewGroup.MarginLayoutParams layoutParams= new
			// ViewGroup.MarginLayoutParams(width, height);
			// layoutParams.leftMargin=padd;
			// holder.imgsContainer.addView(imageView,layoutParams );
			//
			// XImageLoader.load(NetPublicConstant.IMAGE_URL+string, imageView);
			// }

		} else {
			holder.imgsContainer.setVisibility(View.GONE);
		}
		try {
			Group group = genTieItemBean.getUserInfo().getGroup();
			String fid = genTieItemBean.getFid();
			String groupfid = group.getFid();
			if (("0".equals(groupfid) || fid.equals(groupfid))
					&& "0".equals(group.getAllowpost())) {
				holder.name.setText("禁言用户");
			}

		} catch (Exception e) {

		}
		return convertView;
	}

	/**
	 * child两种布局，一种评论，一种查看更多 </br> 0 评论布局 </br> 1 查看更多布局 </br>
	 */
	@Override
	public int getChildTypeCount() {
		// TODO Auto-generated method stub
		return 2;
	}

	/**
	 * child两种布局，一种评论，一种查看更多 </br> 0 评论布局 </br> 1 查看更多布局 </br>
	 */
	@Override
	public int getChildType(int groupPosition, int childPosition) {

		GenTieItemBean gebtiebean = commontList.getList().get(groupPosition);
		if (gebtiebean.getViewMore() == 0)
			return 0;

		int childCount = getChildrenCount(groupPosition);

		return childPosition + 1 == childCount ? 1 : 0;
	}

	@Override
	public View getChildView(int groupPosition, int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {
		if (getChildType(groupPosition, childPosition) == 0) {
			return createCommontView(groupPosition, childPosition, convertView);
		} else {
			return createMoreView(groupPosition, childPosition, convertView);
		}

	}

	private View createMoreView(int groupPosition, int childPosition,
			View convertView) {

		if (convertView == null) {
			convertView = LayoutInflater.from(act).inflate(
					R.layout.item_pinglun_chakan_gengduo, null);
			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					// String author;
					// String authorId;
					// Spanned subject;
					// String dateline;
					// String datelineShow;
					//
					// Spanned message;
					// String useip;
					// String invisible;
					//
					// String status;
					// String comment;

					int gruopPosi = (int) v.getTag();
					Intent intent = new Intent(act,
							ChaKanGengDuoPingKuanActivity.class);
					GenTieItemBean bean = commontList.getList().get(gruopPosi);
					intent.putExtra("tid", bean.getTid());
					intent.putExtra("pid", bean.getPid());
					intent.putExtra("fid", bean.getFid());
					intent.putExtra("imgs", bean.getImg());
					if (bean.getUserInfo() != null) {
						intent.putExtra("nickname", bean.getUserInfo()
								.getNickname());
						intent.putExtra("head", bean.getUserInfo().getHead());
					} else {
						intent.putExtra("nickname", bean.getAuthor());
						intent.putExtra("head", bean.getAuthorId());
					}

					intent.putExtra("subject", bean.getSubject());
					intent.putExtra("datelineShow", bean.getDatelineShow());

					intent.putExtra("message", bean.getMessage());

					act.startActivity(intent);
				}
			});
		}
		convertView.setTag(groupPosition);
		return convertView;
	}

	private View createCommontView(int groupPosition, int childPosition,
			View convertView) {
		ChildViewHolder holder;
		if (convertView == null) {
			holder = new ChildViewHolder();
			convertView = LayoutInflater.from(App.ctx).inflate(
					R.layout.item_luntan_pinglun, null);

			holder.name = (TextView) convertView.findViewById(R.id.name);
			holder.time = (TextView) convertView.findViewById(R.id.time);
			holder.content = (TextView) convertView.findViewById(R.id.content);
			holder.head = (ImageView) convertView.findViewById(R.id.head);

			convertView.setTag(holder);

		} else {
			holder = (ChildViewHolder) convertView.getTag();
		}

		commontBean = commontList.getList().get(groupPosition)
				.getComments().get(childPosition);

		holder.content.setText(commontBean.getComment());
		if (commontBean.getUserInfo() == null) {
			holder.name.setText(commontBean.getAuthor());
		} else {
			holder.name.setText(commontBean.getUserInfo().getNickname()+"回复：");
		}

		holder.time.setText(commontBean.getDatelineShow());

		try {
			if (commontBean.getUserInfo().getHead() == ""
					|| commontBean.getUserInfo().getHead() == null) {
				Bitmap bitmap = BitmapFactory.decodeResource(
						act.getResources(), R.drawable.defaultimage);
				holder.head.setImageBitmap(bitmap);
			} else {
				holder.head.setImageBitmap(null);
				if (!commontBean.getUserInfo().getHead().startsWith("http")) {
					XImageLoader.load(NetPublicConstant.IMAGE_URL
							+ commontBean.getUserInfo().getHead(), holder.head);
				} else {
					XImageLoader.load(commontBean.getUserInfo().getHead(),
							holder.head);
				}
				// XImageLoader.load(NetPublicConstant.IMAGE_URL
				// + commontBean.getUserInfo().getHead(), holder.head);
			}
		} catch (Exception e) {
		}
		try {
			Group group = commontBean.getUserInfo().getGroup();

			String fid = commontList.getList().get(groupPosition).getFid();
			String groupfid = group.getFid();
			if (("0".equals(groupfid) || fid.equals(groupfid))
					&& "0".equals(group.getAllowpost())) {
				holder.name.setText("禁言用户");
			}

		} catch (Exception e) {

		}
		return convertView;

	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {

		return false;
	}

	class GroupViewHolder {
		ImageView head;
		TextView name;
		TextView time;
		TextView content;
		ImageView pinglun;
		View delete;
		ViewGroup imgsContainer;

	}

	class ChildViewHolder {
		ImageView head;
		TextView name;
		TextView time;
		TextView content;

	}
}
